<template>
  <div class="draw">
    <NavHeader title="萤星绘画" />
    <div class="draw-contanier">
      <div class="contanier-left">
        <LeftSider
          :id="id"
          title="绘画"
          :list="chatlist"
          @transmit="getMessage"
          @del="del"
          @clear="clear"
        />
      </div>
      <div class="contanier-right">
        <div ref="chatScroll" class="draw-content" @scroll="handleScroll">
          <span v-for="(message, index) in messagelist" :key="index">
            <div class="draw-list">
              <div class="list-con">
                <div v-if="message.role == 'my'" class="avatar">
                  <img
                    src="@/assets/imgs/avatar.jpg"
                    width="40px"
                    height="40px"
                  />
                </div>

                <div v-if="message.role == 'gpt'" class="avatar">
                  <img
                    src=""
                    width="40px"
                    height="40px"
                  />
                </div>

                <div v-if="message.role == 'my'" class="info">
                  <div class="time">绘画描述{{ message.role }}</div>
                  <div class="tip">
                    {{ message.promote }}
                  </div>
                </div>

                <div v-if="message.role == 'gpt'" class="info">
                  <div class="tip">
                    <div
                      v-if="!currentWindow"
                      v-loading="loading"
                      class="img-load"
                      :element-loading-text="
                        '解析中 ' + (progress === null ? '0%' : progress)
                      "
                      element-loading-spinner="el-icon-loading"
                      element-loading-background="rgba(0, 0, 0, 0.8)"
                    ></div>
                    <img
                      v-else
                      :src="message.text"
                      height="500px"
                      width="500px"
                    />
                  </div>
                  <div v-if="taskId" class="img-btn">
                    <div class="ibtn" @click="changeImg('U1')">P1</div>
                    <div class="ibtn" @click="changeImg('U2')">P2</div>
                    <div class="ibtn" @click="changeImg('U3')">P3</div>
                    <div class="ibtn" @click="changeImg('U3')">P4</div>
                  </div>
                </div>
              </div>
            </div>
          </span>
        </div>
        <div v-show="showSubmit" class="draw-input">
          <div
            v-show="showtToBottomBtn"
            class="to-top"
            @click="scrollToBottom('chatScroll', 'smooth')"
          >
            <i class="el-icon-bottom"></i>
          </div>
          <span class="style-title">风格：</span>
          <el-select v-model="styleValue" placeholder="请选择">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
          <el-input
            v-model="prompt"
            maxlength="200"
            placeholder="请输入内容（英文描述绘图更精准）"
          >
          </el-input>
          <div class="draw-btn" @click="checkTokens">立即生成</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import NavHeader from "@/components/NavHeader";
import LeftSider from "@/components/LeftSider";
import { fetchData } from "@/utils";
import { mjAdd, mjGet, mjUpd } from "@/api/draw";
import { getUserToken } from "@/api/api";
import { getChatHis, updateChatHis, delChatHis } from "@/api/translate";

export default {
  name: "Draw",
  components: {
    NavHeader,
    LeftSider,
  },
  data() {
    return {
      messagelist: [],
      showtToBottomBtn: false,
      prompt: "",
      promote: "",
      options: [
        {
          value: "写实",
          label: "写实",
        },
        {
          value: "抽象",
          label: "抽象",
        },
        {
          value: "印象",
          label: "印象",
        },
        {
          value: "写意",
          label: "写意",
        },
        {
          value: "立体",
          label: "立体",
        },
        {
          value: "扁平插画",
          label: "扁平插画",
        },
        {
          value: "水墨",
          label: "水墨",
        },
        {
          value: "未来主义",
          label: "未来主义",
        },
        {
          value: "波普艺术",
          label: "波普艺术",
        },
        {
          value: "幽默风格",
          label: "幽默风格",
        },
        {
          value: "日韩风",
          label: "日韩风",
        },
        {
          value: "时尚风格",
          label: "时尚风格",
        },
        {
          value: "野兽派",
          label: "野兽派",
        },
        {
          value: "描边插画",
          label: "描边插画",
        },
        {
          value: "肌理插画",
          label: "肌理插画",
        },
        {
          value: "中式古风",
          label: "中式古风",
        },
        {
          value: "彩墨花鸟",
          label: "彩墨花鸟",
        },
        {
          value: "唯美",
          label: "唯美",
        },
        {
          value: "工笔淡彩",
          label: "工笔淡彩",
        },
      ],
      styleValue: "",
      showSubmit: true,
      cacheFilter: { type: "4" },
      id: 0,
      chatlist: [],
      loading: false,
      isAdd: false,
      taskId: "",
      progress: "0%",
      currentWindow: false,
    };
  },
  watch: {
    deep: true,
    progress: {
      handler(n) {
        if (n < "100%") {
          this.currentWindow = false;
        }
      },
    },
    messagelist: {
      handler(n) {
        if (n.length > 2) {
          this.messagelist = n.splice(0, 2);
        }
      },
    },
  },
  created() {
    this.getChatHisList();
  },
  mounted() {},
  methods: {
    handleScroll(e) {
      let scroll =
        e.target.scrollHeight - e.target.clientHeight - e.target.scrollTop;
      if (scroll > 100) {
        this.showtToBottomBtn = true;
      } else {
        this.showtToBottomBtn = false;
      }
    },
    checkTokens() {
      fetchData(getUserToken, 2).then((res) => {
        if (res) {
          this.chat();
        } else {
          this.$message.warning("您的token不足，请充值!");
        }
      });
    },
    chat() {
      if (!this.prompt.trim()) {
        this.$message.warning("请输入内容！");
        return;
      }
      let style = this.styleValue ? "风格：" + this.styleValue + "," : "";
      this.promote = style + this.prompt;
      // fetchData(draw, {
      //   prompt: this.prompt,
      //   size: "1024x1024",
      //   quality: "standard",
      // }).then((res) => {
      //   this.messagelist.push({ text: this.prompt, role: "my" });
      //   this.messagelist.push({ text: res, role: "gpt" });
      //   //每次聊天完之后更新数据库历史记录
      //   this.updateHis();
      //   this.getChatHisList();
      //   this.showSubmit = false;
      // });
      this.loading = true;
      fetchData(
        mjAdd,
        {
          prompt: this.promote,
        },
        false
      ).then((res) => {
        if (res.result) {
          this.taskId = res.result;
          this.updateHis();
          this.mjGet(res.result);
        }
      });
    },

    mjGet(id, type) {
      fetchData(mjGet, id, false)
        .then((res) => {
          this.progress = res.progress || "0%";
          if (!this.isAdd) {
            // this.messagelist.push({
            //   text: this.prompt,
            //   promote: this.promote,
            //   role: "my",
            // });
            this.messagelist.push({
              text: "",
              promote: this.promote,
              role: "gpt",
            });
            this.showSubmit = false;
            this.isAdd = true;
          }
          if (res.progress == "100%") {
            this.loading = false;
            this.progress = "100%";
            this.messagelist[1].text = res.imageUrl;

            if (type != "change") {
              // this.updateHis();
            }
          } else {
            setTimeout(() => {
              this.mjGet(id, type);
            }, 5000);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },

    changeImg(value) {
      if (this.loading) return;
      fetchData(
        mjUpd,
        {
          content: this.taskId ? this.taskId : "" + " " + value,
          notifyHook: "",
          state: "",
        },
        false
      ).then((res) => {
        this.loading = true;
        // this.taskId = res.result;
        this.mjGet(res.result, "change");
      });
      //之前的
      // fetchData(mjUpd, { taskId: this.taskId, index: i }, false).then((res) => {
      //   this.loading = true;
      //   // this.taskId = res.result;
      //   this.mjGet(res.result, "change");
      // });
    },

    getChatHisList(bol) {
      fetchData(
        getChatHis,
        {
          ...this.cacheFilter,
          pagesize: 20,
          pagenum: this.pagenum,
        },
        false
      ).then((res) => {
        this.chatlist = res?.list || [];
        this.pages = res.pages;
        if (bol) {
          // this.getMessage(this.chatlist[0], bol);
          let data = this.chatlist[0];
          data.syncstatus == "01";
          this.messagelist = data.backtext ? JSON.parse(data.backtext) : {}; //data即为子组件发送的数据

          this.id = data.id;
          this.scrollToBottom("chatScroll");
          this.showSubmit = false;
        }
      });
    },
    updateHis() {
      this.messagelist.push({
        text: this.prompt,
        promote: this.promote,
        role: "my",
      });
      fetchData(
        updateChatHis,
        {
          ...this.cacheFilter,
          fromtext: this.messagelist[0].text,
          backtext: JSON.stringify(this.messagelist),
          id: this.id,
          taskid: this.taskId,
        },
        false
      ).then(() => {
        this.getChatHisList(true);
      });
    },
    del(data) {
      if (this.loading) return;
      fetchData(delChatHis, { id: data.id }).then(() => {
        this.$message.success("删除成功!");
        this.pagenum = 1;
        this.getChatHisList();
        this.clear();
      });
    },
    clear() {
      // if (this.loading) return;
      if (this.id == 0) {
        this.$message.warning("当前已是新绘画!");
      } else {
        this.id = 0;
        this.messagelist = [];
        this.showSubmit = true;
        this.isAdd = false;
        this.prompt = "";
        this.styleValue = "";
        this.taskId = "";
      }
    },
    getMessage(data, bol = false) {
      const isFirst = this.chatlist[0].id == data.id;
      if (!this.loading || !isFirst) {
        this.currentWindow = true;
      } else {
        console.log("加载中...");
        this.currentWindow = false;
        this.messagelist.push({
          text: "",
          promote: this.promote,
          role: "gpt",
        });
      }
      data.syncstatus = "01";
      if (!bol) {
        this.taskId = "";
      }
      this.messagelist = data.backtext ? JSON.parse(data.backtext) : {}; //data即为子组件发送的数据
      if (this.messagelist.length == 1) {
        this.messagelist.push({
          text: "",
          promote: this.promote,
          role: "gpt",
        });
      }
      this.id = data.id;
      this.scrollToBottom("chatScroll");
      this.showSubmit = false;
    },
    getMessage2(data) {
      this.id = data.id;
      this.scrollToBottom("chatScroll");
      this.showSubmit = false;
    },
    scrollToBottom(targetElement, behavior = "auto") {
      this.$nextTick(() => {
        // 等待DOM更新完成后才能正确地获取到元素引用
        const target = this.$refs[targetElement];
        target.scrollTo({ top: target.scrollHeight, behavior: behavior });
      });
    },
  },
};
</script>

<style lang="less" scoped>
.draw {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  .draw-contanier {
    flex: 1;
    display: flex;
    overflow: hidden;
    .contanier-left {
      height: 100%;
    }
    .contanier-right {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow-y: hidden;
      .draw-content {
        flex: 1;
        min-width: 800px;
        border-bottom: 1px solid #e5e5e5;
        padding-bottom: 30px;
        overflow-y: auto;
        box-sizing: border-box;
        .draw-list {
          min-width: 800px;
          padding: 20px 0;
          box-sizing: border-box;
          .list-con {
            width: 600px;
            display: flex;
            align-items: center;
            margin: 0 auto;
            .avatar {
              width: 40px;
              height: 40px;
              margin-right: 16px;
              border-radius: 4px;
              // background: #8c8c8c;
            }
            .info {
              min-height: 40px;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              font-size: 14px;
              .time {
                color: #141414;
              }
              .tip {
                color: #8c8c8c;
                &.warning {
                  color: #ef4146;
                }
                .img-load {
                  width: 500px;
                  height: 500px;
                }
              }
              .img-btn {
                display: flex;
                margin-top: 20px;
                .ibtn {
                  width: 36px;
                  height: 36px;
                  line-height: 36px;
                  border-radius: 6px;
                  text-align: center;
                  color: #fff;
                  background-color: #6965ea;
                  cursor: pointer;
                  font-size: 13px;
                  margin-right: 20px;
                }
              }
            }
          }
          &:nth-child(2n + 1) {
            background-color: #fff;
          }
        }
      }
      .draw-input {
        background: #f7f7f8;
        padding: 40px 0;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
        .to-top {
          position: absolute;
          top: -20px;
          right: 100px;
          width: 30px;
          height: 30px;
          background: white;
          border-radius: 50%;
          border: 1px solid #e5e5e5;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 16px;
          color: #999;
          cursor: pointer;
        }
        .style-title {
          color: #606266;
          font-size: 13px;
        }
        /deep/ .el-select {
          width: 132px;
          margin-right: 20px;
          .el-input__inner {
            width: 132px;
          }
        }
        /deep/ .el-input,
        .el-input__inner {
          width: 400px;
        }
        .draw-btn {
          margin-left: 20px;
          border: none;
          outline: none;
          width: 132px;
          height: 36px;
          line-height: 36px;
          border-radius: 6px;
          text-align: center;
          color: #fff;
          background-color: #6965ea;
          cursor: pointer;
          font-size: 13px;
        }
      }
    }
  }
}
</style>
